package com.gqz.aircraftwar.mvp.model.bullet

import android.graphics.*
import com.gqz.aircraftwar.App
import com.gqz.aircraftwar.App.Companion.paint
import com.gqz.aircraftwar.R
import com.gqz.aircraftwar.mvp.model.aircraft.Aircraft
import com.gqz.aircraftwar.mvp.model.aircraft.EnemyAircraft
import com.gqz.aircraftwar.mvp.model.aircraft.PlayerAircraft
import com.gqz.aircraftwar.mvp.model.bomb.BlastManager
import com.gqz.aircraftwar.util.BmpCache
import com.gqz.aircraftwar.util.MyEnum
import com.gqz.aircraftwar.util.v

/**
 * 子弹类
 *
 * @author gqz
 * @data 2020/3/26
 */

open class Bullet(var x: Float = 0f, var y: Float = 0f) {
    private val TAG: String = "Bullet-->"

    var speedx = 0f
    var speedy = 15f
    var damage = 1f
    var free = true
    var special = false
    var dir = MyEnum.Dir.up

    var bmp: Bitmap
    var resId: Int = R.drawable.bullet1

    init {
        bmp = BmpCache.loadBmp(resId)
        bmp = Bitmap.createScaledBitmap(
            bmp, (bmp.width.toFloat() * 0.7f).toInt(),
            (bmp.height * 0.7f).toInt(), false
        )
    }

    fun set(speedx: Float = 0f, speedy: Float = 10f, damage: Float = 1f) {
        this.speedx = speedx
        this.speedy = speedy
        this.damage = damage
    }

    fun hit(air: Aircraft) {
        var rect = RectF(x, y, x + bmp.width, y + bmp.height)
        var isIntersect = rect.intersect(air.getRect())
        if (isIntersect) {
            when (air) {
                is PlayerAircraft -> {
                    v(TAG, "hit--> bullet hit player")
                }
                is EnemyAircraft -> {
                    v(TAG, "hit--> bullet hit enemy")
                }
            }
            if (!special)
                free = true
            air.hp -= this.damage / air.armor
            BlastManager.instance.generateBlastS(PointF(x, y))
            if (air.hp <= 0) {
                air.dead()
            }
        }
    }

    fun inBounds(): Boolean {
        return App.bounds?.contains(x, y) ?: false
    }

    fun resetPos(pos: PointF) {
        x = pos.x
        y = pos.y
    }

    inline fun move() {
        if (!inBounds()) {
            free = true
        } else {
            free = false
        }
        if (!free) {
            x += speedx
            when (dir) {
                MyEnum.Dir.up -> y -= speedy
                MyEnum.Dir.down -> y += speedy
            }
        }
    }

    open fun draw(canvas: Canvas) {
        canvas.drawBitmap(bmp, x, y, paint)
    }

}
